import QtQuick 2.2
import QtQuick.Controls 1.2
import QtGraphicalEffects 1.0
import QtQuick.Controls.Styles 1.2
import QtQuick.Layouts 1.1
import QtGraphicalEffects 1.0
import Utils 1.0
import QtPositioning 5.2
import "."
import "./components/"
import "../javascript/Utils.js" as UtilsJS

MainWindow {
    id: applicationWindow
    title: qsTr("Preço Líder")
    visible: false

    property HomePanel home_panel: Qt.createComponent("qrc:/qml/HomePanel.qml").createObject(body)
    property MapaPanel mapa_panel: Qt.createComponent("qrc:/qml/MapaPanel.qml").createObject(body)
    property FornecedoresPanel fornecedores_panel: null

    property var currentToolBarItem: null
    property var currentToolBarMenu: null
    property string currentPos: "0,0"
    property var path: new Array()

    //Evento usado para iniciar as telas principais
    Component.onCompleted: {
        syncController.createDB();

        body.push(home_panel);
        body.completeTransition();

        body.push(mapa_panel);
        body.completeTransition();

        body.pop();
        body.completeTransition();

        updateToolBar();
        pushPath("Home");

        home_panel.doUpdate();
        applicationWindow.visible = true;
    }

    //Classe usada para receber eventos da aplicacao
    EventFilter {
        //Evento disparado ao pressionar o boto de voltar no dispositivo movel
        onApplicationClose: {
            if(menuBody.visible) {
                hideToolBarMenu();
            } else if(popupMessage.visible) {
                hideMessage();
            } else if (sideMenu.state == "VISIBLE") {
                sideMenu.state = "INVISIBLE"
            } else if (body.depth > 1) {
                if(body.currentItem.back()) {
                    goBack();
                }
            } else {
                Qt.quit();
            }
        }
    }

    //Controllers para acessar as informações necessárias para a interface
    FornecedoresController {
        id: fornecedoresController
    }

    ProdutosController {
        id: produtosController
    }

    ColetasController {
        id: coletasController
    }

    EmbalagensController {
        id: embalagensController
    }

    SyncController {
        id: syncController
        onSendComplete: {syncController.startLoad();}
        onLoadComplete: {body.currentItem.doUpdate(); hideLoading(); sideMenu.state = "INVISIBLE";}
        onSendError: {home_panel.doUpdate(); hideLoading(); sideMenu.state = "INVISIBLE"; showMessage("Erro ao enviar os dados.");}
        onLoadError: {home_panel.doUpdate(); hideLoading(); sideMenu.state = "INVISIBLE"; showMessage("Erro ao carregar os dados.");}
    }

    PositionSource {
        id: positionSource
        onPositionChanged: {
            console.log(positionSource.position.coordinate.latitude+" "+positionSource.position.coordinate.longitude);
            setCurrentPos(positionSource.position.coordinate.latitude+","+positionSource.position.coordinate.longitude);
            mapa_panel.setMapCenter(positionSource.position.coordinate.latitude,positionSource.position.coordinate.longitude);
        }
    }

    //Método usado para atualizar as informacoes da tool bar. Deve ser chamado sempre que ocorrer alguma mudanca de tela
    function updateToolBar() {
        sideMenu.state = "INVISIBLE";

        var item = body.currentItem;
        if(item.showMenuButton) {
            menuButton.visible = true;
            menuButton.text = item.titulo;
        } else {
            menuButton.visible = false;
            backButton.text = item.titulo;
        }
        backButton.visible = !menuButton.visible;

        menuButton.subtitulo = item.subTitulo;
        backButton.subtitulo = item.subTitulo;

        if(currentToolBarItem) {
            currentToolBarItem.parent = null;
        }
        if(item.toolBarItem) {
            currentToolBarItem = item.toolBarItem;
            currentToolBarItem.parent = toolBarScreenItem
        }

        menuBody.visible = false;
        if(currentToolBarMenu) {
            currentToolBarMenu.parent = null;
        }
        if(item.toolBarMenu) {
            currentToolBarMenu = item.toolBarMenu;
            currentToolBarMenu.parent = menuBody;
            currentToolBarMenu.anchors.right = menuBody.right
            currentToolBarMenu.anchors.top = menuBody.top
            currentToolBarMenu.anchors.rightMargin = UtilsJS.dp2px(10)
        } else {
            currentToolBarMenu = null;
        }
    }

    //Fonte que contem os icones usados pela aplicacao
    FontLoader {
        id: webFont
        source: "qrc:/fonts/fontawesome-webfont.ttf"
    }

    //Conteudo da tela
    Item {
        id: bodyRoot
        anchors.top: toolBarItem.bottom
        width: parent.width
        height: parent.height - toolBarItem.height

        StackView {
            id: body
            width: parent.width
            height: parent.height
        }

        Item {
            id: menuBody;
            anchors.fill: parent;
            visible: false
/*
            DropShadow {
                id: dropShadowMenuBody
                height: UtilsJS.dp2px(3)
                horizontalOffset: 0
                verticalOffset: UtilsJS.dp2px(1)
                radius: UtilsJS.dp2px(3)
                samples: 16
                color: "#20000000"
                transparentBorder: true
            }
*/
        }
    }

    //Estilo dos botes usados no side menu
    property Component botoesDrawer: ButtonStyle {
        label: Row {
            spacing: UtilsJS.dp2px(8)
            Text {
                text: control.icon // fa-bars
                color: control.pressed ? "#ffffff" : "#777777"
                font.family: webFont.name
                font.pixelSize: UtilsJS.dp2px(24)
                height: parent.height
                width: height
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
            }
            Text {
                color: control.enabled ? (control.pressed ? "#ffffff" : "#000000") : "#aaaaaa"
                text: qsTr(control.text)
                font.pixelSize: UtilsJS.dp2px(18)
                height: parent.height
                verticalAlignment: Text.AlignVCenter
            }
        }
        background: Rectangle {
            border.width: 0
            color: "#333333"
            opacity: control.pressed ? 0.6 : 0
        }
    }

    //Side menu
    Rectangle {
        id: sideMenu
        x: -width
        y: bodyRoot.y
        width: parent.width
        height: bodyRoot.height
        color: "#00000000"
        border.color: "#00000000"
        state: "INVISIBLE"

        function toggle() {
            if(state == "VISIBLE") state = "INVISIBLE"; else state = "VISIBLE";
            hideToolBarMenu();
        }

        MouseArea {
            width: parent.width - menuContent.width
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 0
            anchors.right: parent.right
            anchors.rightMargin: 0
            anchors.top: parent.top
            anchors.topMargin: 0
            onClicked: sideMenu.toggle()
        }

        Rectangle {
            id: menuContent
            x: -width
            y: 0
            width: UtilsJS.dp2px(250)
            height: parent.height
            color: "#f3f3f3"

            Column {
                width: parent.width
                Button {
                    id: go_home
                    text: "Tela Inicial"
                    style: botoesDrawer
                    width: parent.width
                    height: UtilsJS.dp2px(48)
                    property string icon: ""
                    onClicked: {
                        if (body.depth > 1) {
                            body.pop({immediate: true});
                            body.completeTransition();
                            clearPath();
                            pushPath("Home");
                        }
                        sideMenu.state = "INVISIBLE";
                        updateToolBar();
                    }
                }
                Button {
                    id: go_fornecedores
                    text: "Fornecedores"
                    style: botoesDrawer
                    width: parent.width
                    height: UtilsJS.dp2px(48)
                    property string icon: ""
                    onClicked: exibeFornecedores()
                }
                Button {
                    id: go_mapa
                    text: "Mapa"
                    style: botoesDrawer
                    width: parent.width
                    height: UtilsJS.dp2px(48)
                    property string icon: ""
                    onClicked: exibeMapa();
                }

//                Button {
//                    id: go_mensagens
//                    text: "Mensagens"
//                    style: botoesDrawer
//                    width: parent.width
//                    height: UtilsJS.dp2px(48)
//                    property string icon: ""
//                    onClicked: {
//                        body.push({item: home_panel, immediate: true, replace: (body.depth > 1), destroyOnPop: false});
//                        sideMenu.state = "INVISIBLE";
//                        updateToolBar();
//                    }
//                }
//                Button {
//                    id: go_anotacoes
//                    text: "Anotações"
//                    style: botoesDrawer
//                    width: parent.width
//                    height: UtilsJS.dp2px(48)
//                    property string icon: ""
//                    onClicked: {
//                        body.push({item: home_panel, immediate: true, replace: (body.depth > 1), destroyOnPop: false});
//                        sideMenu.state = "INVISIBLE";
//                        updateToolBar();
//                    }
//                }

                Button {
                    id: sincronizar
                    text: "Sincronizar"
                    style: botoesDrawer
                    width: parent.width
                    height: UtilsJS.dp2px(48)
                    property string icon: ""
                    onClicked: {
                        showPopupLogin();
                    }
                }
            }
        }

        states: [
            State {
                name: "INVISIBLE"
                PropertyChanges { target: sideMenu; color: "#00000000"}
                PropertyChanges { target: sideMenu; x: -sideMenu.width}

                PropertyChanges { target: menuContent; x: -menuContent.width}
            },
            State {
                name: "VISIBLE"
                PropertyChanges { target: sideMenu; color: "#50000000"}
                PropertyChanges { target: sideMenu; x: 0}

                PropertyChanges { target: menuContent; x: 0}
            }
        ]

        transitions: [
            Transition {
                from: "INVISIBLE"
                to: "VISIBLE"
                ColorAnimation { target: sideMenu; properties: "color"; to: "#50000000"; duration: 500; easing { type: Easing.OutQuint }}
                NumberAnimation { target: sideMenu; properties: "x"; to: 0; duration: 1}

                NumberAnimation { target: menuContent; properties: "x"; to: 0; duration: 500; easing { type: Easing.OutQuint }}
            },
            Transition {
                from: "VISIBLE"
                to: "INVISIBLE"
                ColorAnimation { target: sideMenu; properties: "color"; to: "#00000000";  duration: 500; easing { type: Easing.OutQuint }}

                NumberAnimation { target: menuContent; properties: "x"; to: -menuContent.width; duration: 500; easing { type: Easing.OutQuint }}
            }
        ]

    }

//Métodos auxiliares para facilitar o gerenciamento/transicao das telas
    function screenLock() {
//        topRectangle1.visible = true;
        topRectangle2.visible = true;
    }

    function screenUnlock() {
//        topRectangle1.visible = false;
        topRectangle2.visible = false;
    }

    function showLoading() {
        screenLock();
        loading.visible = true;
    }

    function hideLoading() {
        screenUnlock();
        loading.visible = false;
    }

    function showPopupLogin() {
        screenLock();
        popupLogin.visible = true;
    }

    function hidePopupLogin() {
        screenUnlock();
        popupLogin.visible = false;
    }

    function showMessage(message) {
        screenLock();
        popupMessageText.text = message;
        popupMessage.visible = true;
    }

    function hideMessage() {
        screenUnlock();
        popupMessage.visible = false;
    }

    function showPath() {
        var i;
        var strPath = "";

        for(i=0; i<path.length; i++) {
            if(i>0) strPath += " -> "

            strPath += path[i].descricao;
            if(path[i].detalhe.length>0) {
                strPath += "(" + path[i].detalhe + ")";
            }
        }

        showMessage(strPath);
    }

    function pushPath(descricao) {
        var pathItem = {descricao: descricao, detalhe:""};
        path.push(pathItem);
    }

    function popPath() {
        path.pop();
        if(path.length==0) {
            pushPath("Home")
        }
    }

    function clearPath() {
        path.length = 0;
    }

    function detalhePath(detalhe) {
        path[path.length-1].detalhe = detalhe;
    }

    function showToolBarMenu() {
        if(currentToolBarMenu) {
            sideMenu.state = "INVISIBLE"
            menuBody.visible = true;
//            dropShadowMenuBody.anchors.fill = currentToolBarMenu
//            dropShadowMenuBody.source = currentToolBarMenu
        }
    }

    function hideToolBarMenu() {
        menuBody.visible = false;
//        dropShadowMenuBody.anchors.fill = null
//        dropShadowMenuBody.source = null
    }

    function toggleToolBarMenu() {
        if(menuBody.visible) {
            hideToolBarMenu();
        } else {
            showToolBarMenu();
        }
    }

    function goBack() {
        popPath();
        body.pop();
        body.completeTransition();

        body.currentItem.doUpdate();
        updateToolBar();
    }

    function setCurrentPos(pos) {
        currentPos = pos;
    }

    function exibeMapa() {
        clearPath();
        pushPath("Mapa");

        body.push({item: mapa_panel, immediate: true, replace: (body.depth > 1), destroyOnPop: false});
        body.completeTransition();
        mapa_panel.doUpdate();
        updateToolBar();
    }

    function exibeFornecedores() {
        clearPath();
        pushPath("Fornecedores");

        if(fornecedores_panel==null) {
            var componentFornecedores = Qt.createComponent("qrc:/qml/FornecedoresPanel.qml");
            fornecedores_panel = componentFornecedores.createObject(body);
        }

        body.push({item: fornecedores_panel, immediate: true, replace: (body.depth > 1), destroyOnPop: false});
        body.completeTransition();
        fornecedores_panel.doUpdate();
        updateToolBar();
    }

    function exibeProdutos(fornecedorId,fornecedorNome) {
        pushPath("Produtos");

        var ProdutosComponent = Qt.createComponent("qrc:/qml/ProdutosPanel.qml");
        var produtosPanel = ProdutosComponent.createObject(body);
        produtosPanel.subTitulo = fornecedorNome;
        produtosPanel.fornecedorId = fornecedorId;

        body.push({item: produtosPanel, destroyOnPop: true});
        body.completeTransition();
        produtosPanel.doUpdate();
        updateToolBar();
    }

    function fazerColeta(fornecedorId, fornecedorNome, produtoId) {
        pushPath("Coleta");

        var coletaPrecoComponent = Qt.createComponent("qrc:/qml/ColetaPrecoPanel.qml");
        var coletaPrecoPanel = coletaPrecoComponent.createObject(body);
        coletaPrecoPanel.subTitulo = fornecedorNome;
        coletaPrecoPanel.fornecedorId = fornecedorId;
        coletaPrecoPanel.produtoId = produtoId;

        body.push({item: coletaPrecoPanel, destroyOnPop: true});
        body.completeTransition();
        coletaPrecoPanel.doUpdate();
        updateToolBar();
    }

    //Tool bar
    Rectangle {
        id: toolBarItem
        width: parent.width
        height: UtilsJS.dp2px(48)
        color: "black"
/*
        DropShadow {
            anchors.fill: top_menu
            source: top_menu
            height: UtilsJS.dp2px(3)
            horizontalOffset: 0
            verticalOffset: UtilsJS.dp2px(1)
            radius: UtilsJS.dp2px(3)
            samples: 16
            color: "#20000000"
            transparentBorder: true
        }
*/
        ToolBar {
            id: top_menu
            anchors.fill: parent
            style: ToolBarStyle {
                padding {left: UtilsJS.dp2px(-10); right: 0; top: 0; bottom: 0;}
                background: Rectangle {
                    color: "#d9d9d9"
                }
            }

            ToolButton {
                id: menuButton
                text: "Preço Líder"
                height: parent.height
                width: UtilsJS.dp2px(175)
                anchors.verticalCenter: parent.verticalCenter
                onClicked: sideMenu.toggle()

                property var subtitulo: null

                style: ButtonStyle {
                    label: Row {
                        spacing: UtilsJS.dp2px(8)
                        Text {
                            text: "" // fa-bars
                            color: "#777777"
                            font.family: webFont.name
                            font.pixelSize: UtilsJS.dp2px(24)
                            height: parent.height
                            width: UtilsJS.dp2px(24)
                            verticalAlignment: Text.AlignVCenter
                            horizontalAlignment: Text.AlignLeft
                        }
                        Text {
                            text: "" // fa-trophy
                            color: "#ffbd21"
                            font.family: webFont.name
                            font.pixelSize: UtilsJS.dp2px(32)
                            height: parent.height
                            verticalAlignment: Text.AlignVCenter
                        }
                        Column {
                            width: UtilsJS.dp2px(300)

                            Text {
                                height: control.subtitulo?parent.parent.height-menuSubtituloText.height:parent.parent.height
                                color: "#000000"
                                text: control.text
                                font.pixelSize: UtilsJS.dp2px(18)
                                verticalAlignment: Text.AlignVCenter
                            }

                            Text {
                                id: menuSubtituloText
                                visible: control.subtitulo?true:false
                                color: "#000000"
                                text: control.subtitulo?control.subtitulo:""
                                font.pixelSize: UtilsJS.dp2px(14);
                                verticalAlignment: Text.AlignVCenter
                            }
                        }

                    }
                    background: Rectangle {
                        border.width: 0
                        color: control.pressed ? "#33b5e5" : "transparent"
                    }
                }
            }

            ToolButton {
                id: backButton
                text: ""
                visible: false;
                height: parent.height
                width: UtilsJS.dp2px(175)
                anchors.verticalCenter: parent.verticalCenter
                onClicked: goBack()

                property var subtitulo: null

                style: ButtonStyle {
                    label: Row {
                        spacing: UtilsJS.dp2px(8)
                        Text {
                            text: ""
                            color: "#777777"
                            font.family: webFont.name
                            font.pixelSize: UtilsJS.dp2px(24)
                            height: parent.height
                            width:  UtilsJS.dp2px(24)
                            verticalAlignment: Text.AlignVCenter
                            horizontalAlignment: Text.AlignRight
                        }
                        Text {
                            text: "" // fa-trophy
                            color: "#ffbd21"
                            font.family: webFont.name
                            font.pixelSize: UtilsJS.dp2px(32)
                            height: parent.height
                            verticalAlignment: Text.AlignVCenter
                        }
                        Column {
                            width: UtilsJS.dp2px(300)

                            Text {
                                height: control.subtitulo?parent.parent.height-backSubtituloText.height:parent.parent.height
                                color: "#000000"
                                text: control.text
                                font.pixelSize: UtilsJS.dp2px(18)
                                verticalAlignment: Text.AlignVCenter
                            }

                            Text {
                                id: backSubtituloText
                                visible: control.subtitulo?true:false
                                color: "#000000"
                                text: control.subtitulo?control.subtitulo:""
                                font.pixelSize: UtilsJS.dp2px(14);
                                verticalAlignment: Text.AlignVCenter
                            }
                        }
                    }
                    background: Rectangle {
                        border.width: 0
                        color: control.pressed ? "#33b5e5" : "transparent"
                    }
                }
            }

            Row {
                anchors.right: parent.right
                anchors.rightMargin: UtilsJS.dp2px(5)
                anchors.top: parent.top
                anchors.bottom: parent.bottom
                spacing: UtilsJS.dp2px(5)

                Row {
                    id: toolBarScreenItem
                    anchors.top: parent.top
                    anchors.bottom: parent.bottom
                    anchors.margins: UtilsJS.dp2px(2)
                }

                Button {
                    width: UtilsJS.dp2px(30);
                    anchors.top: parent.top
                    anchors.bottom: parent.bottom
                    anchors.leftMargin: UtilsJS.dp2px(3)
                    anchors.rightMargin: UtilsJS.dp2px(3)
                    onClicked: toggleToolBarMenu()

                    style: ButtonStyle {
                        label: Text {
                                text: ""
                                color: "#777777"
                                font.family: webFont.name
                                font.pixelSize: UtilsJS.dp2px(24)
                                height: parent.height
                                width:  UtilsJS.dp2px(24)
                                verticalAlignment: Text.AlignVCenter
                                horizontalAlignment: Text.AlignHCenter
                        }
                        background: Rectangle {
                            border.width: 0
                            color: control.pressed ? "#33b5e5" : "transparent"
                        }
                    }
                }

            }
        }
/*
        Rectangle {
            id: topRectangle1
            anchors.fill: parent
            color: "#88000000"
            visible: false

            MouseArea {
                anchors.fill: parent
            }
        }
*/
    }

    //Retangulo usado para encobrir a tela temporariamente, impedindo o usuario de interagir com a aplicação
    Rectangle {
        id: topRectangle2
        anchors.fill: parent
        color: "#88000000"
        visible: false

        MouseArea {
            anchors.fill: parent
        }
    }

    //Componente com animacao de Loading (progress bar)
    Rectangle {
        id: loading
        visible: false

        anchors.left: parent.left
        anchors.leftMargin: UtilsJS.dp2px(10)
        anchors.right: parent.right
        anchors.rightMargin: UtilsJS.dp2px(10)

        anchors.verticalCenter: parent.verticalCenter

        height: loadingContent.height + 2*loadingContent.anchors.margins
        color: "black"

        Column {
            id: loadingContent
            spacing: UtilsJS.dp2px(5)

            anchors.left: parent.left
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.margins: UtilsJS.dp2px(10)

            Text {
                text: qsTr("Sincronizando dados...")
                color: "white"
            }

            Rectangle {
                width: parent.width
                height: UtilsJS.dp2px(2)
                color: "white"
            }

            Rectangle {
                width: parent.width
                height: UtilsJS.dp2px(60)
                color: "#000000"
                ProgressBar {
                    anchors.centerIn: parent
                    width: parent.width - UtilsJS.dp2px(20)
                    indeterminate: true
                }
            }
        }
    }

    //Componente usado para exibir popup de mensagem.
    Rectangle {
        id: popupMessage
        visible: false

        anchors.left: parent.left
        anchors.leftMargin: UtilsJS.dp2px(10)
        anchors.right: parent.right
        anchors.rightMargin: UtilsJS.dp2px(10)

        anchors.verticalCenter: parent.verticalCenter

        height: popupMessageContent.height + 2*popupMessageContent.anchors.margins
        color: "black"

        Column {
            id: popupMessageContent
            spacing: UtilsJS.dp2px(5)

            anchors.left: parent.left
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.margins: UtilsJS.dp2px(10)

            Text {
                text: qsTr("Informação:")
                color: "white"
            }

            Rectangle {
                width: parent.width
                height: UtilsJS.dp2px(2)
                color: "white"
            }

            Rectangle {
                width: parent.width
                height: popupMessageText.height
                color: "black"
                Text {
                    id: popupMessageText
                    color: "white"
                    width: parent.width - UtilsJS.dp2px(20)
                    wrapMode: Text.WordWrap
                }
            }

            Item {
                width: parent.width
                height: UtilsJS.dp2px(50)

                Button {
                    text: "Ok"
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.bottom: parent.bottom
                    onClicked: {
                        hideMessage();
                    }
                }

            }

        }
    }


    //Componente usado para exibir popup de login.
    Rectangle {
        id: popupLogin
        visible: false

        anchors.left: parent.left
        anchors.leftMargin: UtilsJS.dp2px(10)
        anchors.right: parent.right
        anchors.rightMargin: UtilsJS.dp2px(10)

        anchors.verticalCenter: parent.verticalCenter

        height: popupLoginContent.height + 2*popupLoginContent.anchors.margins
        color: "black"

        Column {
            id: popupLoginContent
            spacing: UtilsJS.dp2px(5)

            anchors.left: parent.left
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.margins: UtilsJS.dp2px(10)

            Text {
                text: qsTr("Login")
                color: "white"
            }

            Rectangle {
                width: parent.width
                height: UtilsJS.dp2px(2)
                color: "white"
            }

            Text {
                text: qsTr("Usuario:")
                color: "white"
            }

            TextField {
                id: userLogin
                width: parent.width
            }

            Text {
                text: qsTr("Senha:")
                color: "white"
            }

            TextField {
                id: userPassword
                width: parent.width
            }

            Row {
                spacing: UtilsJS.dp2px(20)
                anchors.horizontalCenter: parent.horizontalCenter
                height: UtilsJS.dp2px(50)

                Button {
                    text: "Ok"
                    anchors.bottom: parent.bottom
                    onClicked: {
                        hidePopupLogin();
                        showLoading();
                        syncController.startSend();
                    }
                }

                Button {
                    text: "Cancel"
                    anchors.bottom: parent.bottom
                    onClicked: {
                        hidePopupLogin();
                    }
                }

            }

        }
    }
}

